package com.hongshan.wallet.core

import android.annotation.SuppressLint
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.databinding.ViewDataBinding
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.webkit.JavascriptInterface
import android.webkit.ValueCallback
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import com.alibaba.android.arouter.facade.annotation.Route
import com.hongshan.wallet.R
import com.hongshan.wallet.base.MyActivity
import com.hongshan.wallet.base.MyViewModel
import com.hongshan.wallet.bean.BindInfoBean
import com.hongshan.wallet.core.wallet.BindAccountActivity
import com.hongshan.wallet.http.HttpClient
import com.hongshan.wallet.log
import com.hongshan.wallet.router.RouterIndex
import com.hongshan.wallet.toast
import com.hongshan.wallet.tryRun
import com.hongshan.wallet.util.MyActivityManager
import kotlinx.android.synthetic.main.activity_web.*
import kotlinx.android.synthetic.main.appbar.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.launch


/**
 * Copyright Zhangxx.
 * Copyright (c) 2019
 * All rights reserved
 *
 * @project  : Wallet
 * @package  : com.example.wallet.core
 * @author   : zhangxx
 * @date     : 2019/3/27
 * @email    : qq957413212@hotmail.com
 * @desc     : //TUDO
 */
@Route(path = RouterIndex.WEB)
class WebActivity: MyActivity<ViewDataBinding, MyViewModel>() {

    var url:String? =null

    private val uploadFiles: ValueCallback<Array<Uri>>? = null

    override fun initVariableId() = 0

    override fun initContentView(savedInstanceState: Bundle?) = R.layout.activity_web

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        url = intent.getStringExtra("url")
        initWebView()
        webView.loadUrl(url)
    }

    @SuppressLint("SetJavaScriptEnabled", "AddJavascriptInterface")
    private fun initWebView() {
        val settings = webView.settings
        settings.allowContentAccess = true
        settings.allowFileAccess = true
        settings.allowFileAccessFromFileURLs = true
        settings.allowUniversalAccessFromFileURLs = true
        settings.setAppCacheEnabled(true)
        settings.displayZoomControls = false
        settings.javaScriptCanOpenWindowsAutomatically = true
        settings.javaScriptEnabled = true
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.mixedContentMode = android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
        }
        settings.layoutAlgorithm = WebSettings.LayoutAlgorithm.NARROW_COLUMNS
        settings.setSupportZoom(true)
        webView.requestFocus()
        webView.requestFocusFromTouch()
        webView.addJavascriptInterface(WebInterface(), "wallet")
        webView.webChromeClient = MyWebChromeClient(tvTitle,this,uploadFiles)
        webView.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                this@WebActivity.url = url
                view.loadUrl(url)
                log("url: $url")
                return true
            }
        }
    }

    override fun onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack()
        } else {
            super.onBackPressed()
        }
    }

    inner class WebInterface{
        @JavascriptInterface
        fun log(msg:String){
            toast(msg)
        }

        @JavascriptInterface
        fun copy(text:String) {
            //获取剪贴板管理器：
            val cm = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
            // 创建普通字符型ClipData
            val mClipData = ClipData.newPlainText("Label", text)
            // 将ClipData内容放到系统剪贴板里。
            cm.setPrimaryClip(mClipData)
            toast("复制成功")
        }

        @JavascriptInterface
        fun getInviteCode() {
            GlobalScope.launch(Dispatchers.Main) {
                val result = GlobalScope.async {
                    tryRun { HttpClient.httpApi.myInvite().execute() }
                }
                val body = result.await()?.body()
                if (body?.code == 0) {
                    webView.loadUrl("Javascript:setData('${body.data}')")
                }
            }
        }

        @JavascriptInterface
        fun back_app(user_id:String){
            MyActivityManager.getActivity(BindAccountActivity::class.java)?.run {
                if (vm.accountBean?.type == BindInfoBean.ACCOUNT_TYPE_ALIPAY){
                    vm.accountBean?.user_id = user_id
                    vm.initState()
                }
            }
            finish()
        }
    }

    companion object {
        const val REQUEST_CODE_CHOOSE_FILE = 4000
    }
}